# -*- coding: UTF-8 -*-
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.conf import settings

from .models import Server,ServerHardInfo
from .forms import ServerForm, Server_Search_Form,ServerHardInfoForm,ServerHardInfo_SearchForm
from public.function import Public
from saltstack.salt_api import SaltAPI
from cmdb.models import Server

import json
from django.shortcuts import get_object_or_404, render, redirect
from django.views.generic import View
from django.views.generic.list import ListView




from django.forms.models import model_to_dict



@login_required
def index(request):
    return render(request, 'cmdb/index.html', locals())


@login_required()
def help(request):
    return render(request, 'cmdb/help.html', locals())


@login_required()
def server_list(request):
    cls=Public()
    return cls.url_get(request,app="cmdb",template="server_list",
                  form=ServerForm,models=Server,
                  search_form=Server_Search_Form)


@login_required()
def new_server_list(request):
    return render(request,"cmdb/new_server_list.html",locals())








@login_required()
def ajax_server_list(request):
    rowslist=[
        {
            "OrderID": "1",
            "CustomerID": "WILMK",
            "OrderDate": "1996-07-04 00:00:00",
            "Freight": "32.3800",
            "ShipName": "Vins et alcools Chevalier"
        },
        {
            "OrderID": "2",
            "CustomerID": "TRADH",
            "OrderDate": "1996-07-05 00:00:00",
            "Freight": "11.6100",
            "ShipName": None
        },
        {
            "OrderID": "3",
            "CustomerID": "HANAR",
            "OrderDate": "1996-07-08 00:00:00",
            "Freight": "65.8300",
            "ShipName": "Hanari Carnes"
        }]
    # rowslist=model_to_dict(Server,exclude=[])
    return JsonResponse(rowslist,safe=False)


class ServerView(View):
    model = Server
    template_name = "cmdb/server_list.html"


    @login_required()
    def get(self,request, *args, **kwargs):
        return HttpResponse('test')

    @login_required()
    def post(self,request, *args, **kwargs):
        pass


    # def get_context_data(self, **kwargs):
    #     context = super(ServerView, self).get_context_data(**kwargs)









@login_required()
def server_hardinfo(request):
    cls= Public()
    return cls.url_get(request,app="cmdb",template="server_hardinfo",
                form=ServerHardInfoForm,models=ServerHardInfo,
                search_form=ServerHardInfo_SearchForm)


@login_required()
def ssh_views(request):
    if request.method != "POST":
        return HttpResponse(status=403)
    option=request.GET.get('option','')
    if option == "update_system_hard_info":
        server_id = request.POST.get("serverid")
        server_id = server_id.split('.')
        t = [int(x.strip()) for x in server_id]
        Saltapi=SaltAPI(url=settings.SALT_API_URL,username=settings.SALT_API_USER,password=settings.SALT_API_PASSWD)
        for sid in t:
            server = get_object_or_404(Server, pk=int(sid))
            minion_id=server.ip
            saltresult=Saltapi.remote_noarg_execution(minion_id,'grains.items')
            ret=saltresult[minion_id]
            dic={}
            dic['ip'] = server
            dic['osver']=" ".join([ret['osfullname'],
                                   "release",
                                   ret['osrelease'],
                                   ret['osarch'],
                                   ret['oscodename']])
            dic['kernel']=ret['kernelrelease']
            dic['cpu_model']=ret['cpu_model']
            dic['cpu_num']=ret['num_cpus']
            dic['mem']=ret['mem_total']
            dic['disk']=ret['disk']
            dic['hostname']=ret['localhost']
            dic['product']=ret['productname']
            dic['all_info']=json.dumps(ret)
            dic['id']=sid
            add = ServerHardInfo(**dic)
            add.save()


    return JsonResponse({'msg': "success"}, safe=False)





